import Flutter
import UIKit
import UserNotifications

@main
@objc class AppDelegate: FlutterAppDelegate {
  private var pushToken: String = ""
  
  override func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
  ) -> Bool {
    // 注册 Flutter Channel
    let controller = window?.rootViewController as! FlutterViewController
    let pushChannel = FlutterMethodChannel(name: "com.yn_goods.push_notification", binaryMessenger: controller.binaryMessenger)
    
    pushChannel.setMethodCallHandler { [weak self] (call, result) in
      guard let self = self else { return }
      
      if call.method == "getToken" {
        result(self.pushToken)
      } else if call.method == "requestPermission" {
        self.requestNotificationPermission { granted in
          result(granted)
        }
      } else {
        result(FlutterMethodNotImplemented)
      }
    }
    
    // 注册推送
    registerForPushNotifications()
    
    GeneratedPluginRegistrant.register(with: self)
    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  }
  
  // 注册推送通知
  private func registerForPushNotifications() {
    UNUserNotificationCenter.current().delegate = self
    
    // 注册远程推送
    UIApplication.shared.registerForRemoteNotifications()
  }
  
  // 请求通知权限
  private func requestNotificationPermission(completion: @escaping (Bool) -> Void) {
    UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { granted, _ in
      DispatchQueue.main.async {
        completion(granted)
      }
    }
  }
  
  // 获取设备 token
  override func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    let tokenParts = deviceToken.map { data in String(format: "%02.2hhx", data) }
    let token = tokenParts.joined()
    self.pushToken = token
    print("Device Token: \(token)")
  }
  
  // 注册失败
  override func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
    print("Failed to register for remote notifications: \(error)")
  }
}
